<script>
  import { base64ToPath } from 'image-tools';
  import sheep from '@/sheep';

  // #ifdef APP-PLUS
  const testModule = uni.requireNativePlugin('da-comfile');
  // #endif

  export default {
    name: 'pafMagage',
    props: {
      imageList: {
        type: Array,
        default: () => {
          return [];
        },
      },
    },
    data() {
      return {
        list: [],
        posterUrl: '',
      };
    },
    mounted() {
      uni.$on('managePdf', (imageArr) => {
        this.list = imageArr;
      });
    },
    methods: {
      async receiveRenderData(e) {
        this.base64ToFile(e, '拾亲.pdf', (path) => {
          let platform = uni.getSystemInfoSync().platform;
          if (platform == 'android') {
            uni.hideLoading()
            plus.runtime.openFile(path);
          } else {
            uni.hideLoading()
            plus.runtime.openFile(path);
          }
        });
      },
      /**
       * base64字符串转成文件
       * @param {String} base64Str // 允许包含前缀
       * @param {String} fileName // 文件名称：1663061363470.xlsx
       * @param {Object} callback  // 返回本地路径径URL，file:///xxx/doc/1663062980631.xlsx
       */
      base64ToFile(base64Str, fileName, callback) {

        // 去除base64前缀
        var index = base64Str.indexOf(',');
        var base64Str = base64Str.slice(index + 1, base64Str.length);

        plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
          fs.root.getFile(fileName, { create: true }, function(entry) {

            // 获得本地路径URL，file:///xxx/doc/1663062980631.xlsx
            var fullPath = entry.fullPath;

            let platform = uni.getSystemInfoSync().platform;
            if (platform == 'android') {
              var Base64 = plus.android.importClass('android.util.Base64');
              var FileOutputStream = plus.android.importClass('java.io.FileOutputStream');
              try {
                var out = new FileOutputStream(fullPath);
                // 此处Base64.decode有长度限制，如果不能满足需求，可以考虑换成官方原生插件市场的【Base64转文件】
                // var bytes = Base64.decode(base64Str, Base64.DEFAULT);
                var filePath = testModule.saveBase64File(base64Str, fileName);
                callback && callback(filePath);
                // console.log(filePath);
                // out.write(filePath);
                // out.close();
                // 回调

              } catch (e) {
                console.log(e.message);
              }
            } else if (platform == 'ios') {
              var NSData = plus.ios.importClass('NSData');
              var nsData = new NSData();
              nsData = nsData.initWithBase64EncodedStringoptions(base64Str, 0);
              if (nsData) {
                nsData.plusCallMethod({ writeToFile: fullPath, atomically: true });
                plus.ios.deleteObject(nsData);
              }
              // 回调
              callback && callback(entry.toLocalURL());
            }
          });
        });
      },
    },
  };
</script>
<script module="managePdf" lang="renderjs">
  import {
    jsPDF
  } from 'jspdf';
  export default {
    methods: {
      async save(newVal,oldVal,ownerFun,vm) {
        console.log(plus.io)
        if(!!newVal && newVal != [] && newVal.length > 0){
          const PDF = new jsPDF('p', 'px', [375, 667]);
          for (let i = 0; i < newVal.length; i++) {
            console.log(i)
            const url = newVal[i];
            // PDF.addImage(url, 'png', 1, 1, 375, 667);
            PDF.addImage(url, 'png', 0, 0, 375, 667);
            PDF.addPage([375, 667]);
          }
          const targetPage = PDF.internal.getNumberOfPages();
          PDF.deletePage(targetPage);
          let blobUrl = PDF.output('datauristring');
          ownerFun.callMethod('receiveRenderData',blobUrl)
          // 删除最后一页留白
          //await PDF.save('PDF存档.pdf');
          // 删除最后一页留白
        }
      }
    },
  }
</script>

<template>
  <view :list="list" :change:list="managePdf.save" class="renderjs" id="renderjs-view"></view>
</template>

<style scoped lang="scss">

</style>